package com.atrix.CinemaView.controller;

import com.atrix.CinemaView.exception.MessageException;
import com.atrix.CinemaView.pojo.dto.info.PhotoContainerInfo;
import com.atrix.CinemaView.pojo.dto.PhotoStreamData;
import com.atrix.CinemaView.pojo.vo.R;
import com.atrix.CinemaView.service.PhotoService;
import com.atrix.CinemaView.utils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/api/photo")
@Slf4j
@Api("图片控制器")
public class PhotoController {
    @Autowired
    PhotoService photoService;
    
    @GetMapping
    @ApiOperation("从所有的图片容器中获取随机图片")
    public void getRandomPhoto(HttpServletResponse response) {
        PhotoStreamData photo = photoService.getRandomPhoto();
        response.setContentType("image/" + photo.getType());
        FileUtil.outputFile(photo, response);
    }
    
    @GetMapping("/{index}")
    @ApiOperation("从索引指定的图片容器中获取图片")
    public void getRandomInContainer(@ApiParam("图片容器索引") @PathVariable("index") String index,
                                     HttpServletResponse response) {
        int i = parseIndex(index);
        PhotoStreamData photo = photoService.getRandomInContainer(i);
        response.setContentType("image/" + photo.getType());
        FileUtil.outputFile(photo, response);
    }
    
    @GetMapping("/{containerIndex}/{index}")
    @ApiOperation("从索引指定的图片容器中获取索引指定的图片")
    public void getPhoto(@ApiParam("图片容器索引") @PathVariable("containerIndex") String containerIndex,
                         @ApiParam("容器内图片索引") @PathVariable("index") String index,
                         HttpServletResponse response) {
        int ci = parseIndex(containerIndex);
        int i = parseIndex(index);
        PhotoStreamData photo = photoService.getPhoto(ci, i);
        response.setContentType("image/" + photo.getType());
        FileUtil.outputFile(photo, response);
    }
    
    @GetMapping("/info")
    @ApiOperation("获取图片容器信息")
    public R<List<PhotoContainerInfo>> getContainerInfo() {
        return R.<List<PhotoContainerInfo>>success().
                setData(photoService.getAllContainerInfo());
    }
    
    private int parseIndex(String index) {
        if (index == null) {
            throw new MessageException("传入的索引错误");
        }
        try {
            return Integer.parseInt(index);
        } catch (NumberFormatException e) {
            throw new MessageException("传入的索引错误");
        }
    }
}
